#!/usr/bin/env sh

echo "::format disk"
cfdisk /dev/sda

mkfs.ext2 /dev/sda1
mkswap /dev/sda2
mkfs.ext4 /dev/sda3

echo "::mount /root:"
mkdir -p /mnt/funtoo
mount /dev/sda3 /mnt/funtoo
swapon /dev/sda2

echo "::set date:"
ntpdate ntp.aliyun.com

echo "::install stage3:"
cd /mnt/funtoo
scap damon@192.168.3.240:/home/cinnamon-stage3-latest.tar.xz .
tar xpvf cinnamon-stage3-latest.tar.xz --xattrs-include='*' --numeric-owner

mv /boot /funtoo_boot
mkdir /boot

scap damon@192.168.3.240:/home/meta-repo-latest.tar.xz .
tar -xvJf meta-repo-latest.tar.xz

echo "::config portage:"
echo 'MAKEOPTS="-j2"' >> /mnt/funtoo/etc/portage/make.conf
echo 'FEATURES="buildpkg getbinpkg"' >> /mnt/funtoo/etc/portage/make.conf
echo '#PORTAGE_BINHOST="http://binhost.com/packages"' >> /mnt/funtoo/etc/portage/make.conf
echo 'ACCEPT_LICENSE="*"' >> /mnt/funtoo/etc/portage/make.conf
echo 'I10N="en-US zh-CN en zh"' >> /mnt/funtoo/etc/portage/make.conf
echo 'LINGUAS="en-US zh-CN en zh"' >> /mnt/funtoo/etc/portage/make.conf

echo "::chroot to new root:"
/mnt/funtoo
mount -t proc none proc
mount --rbind /sys sys
mount --rbind /dev dev

echo "::config portage:"
cp /etc/resolv.conf /mnt/funtoo/etc/

echo "::chroot to new root:"
/mnt/funtoo
env -i HOME=/root TERM=$TERM chroot . bash -l
source /etc/profile
export PS1="(chroot) $PS1"
# env-update && source /etc/profile && export PS1="(chroot) ${PS1}"

ping -c 5 baidu.com

echo "::ego sync"
ego sync
emerge -auDN @world

echo "::upgraded config"
blkid
lsblk -f
sleep 3
nano -w /etc/fstab

echo "::kernel install:"
# emerge -s debian-sources
mount /dev/sda1 /boot
cp .funtoo_boot/* /boot/

ls /boot

echo "tool install:"
# emerge -av linux-firmware
emerge linux-firmware networkmanager dhcpcd
rc-update add NetworkManager default
rc-update add dhcpcd default


echo "::grub install:"
emerge -av grub microcode iucode_tool
grub-install --target=i386-pc --no-floppy /dev/sda
ego boot update

echo "::set root passwd:"
passwd

echo "::add user:"
useradd -m -G users,wheel,audio -s /bin/bash damon
passwd damon

# exit
echo "::finish: now you can 'exit && reboot'."
